import { defineConfig, loadEnv } from "vite";
import vue from "@vitejs/plugin-vue";
import { resolve } from "path";
import { VitePWA } from "vite-plugin-pwa";
import Components from "unplugin-vue-components/vite";

export default defineConfig(({ mode }) => {
  const env = loadEnv(mode, process.cwd());
  return {
    plugins: [
      vue(),
      //配置pwa手机主屏幕外链
      VitePWA({
        registerType: "autoUpdate",
        devOptions: {
          enabled: true, //是否支持开发模式也使pwa生效
        },
        manifest: false,
        workbox: {
          globPatterns: ["**/*.{js,css,html,png,svg}"],
          runtimeCaching: [
            {
              urlPattern: new RegExp(`^${env.VITE_BACKEND_DOMAIN}/.*$`), // 替换为你的 API 地址
              handler: "NetworkFirst", // 运行时缓存策略
              options: {
                cacheName: "api-cache", // 缓存名称
                expiration: {
                  maxEntries: 50, // 缓存最多 50 个条目
                  maxAgeSeconds: 24 * 60 * 60, // 缓存时间为 1 天
                },
              },
            },
          ],
          maximumFileSizeToCacheInBytes: 4 * 1024 * 1024, // 将限制提高到 4 MB
        },
      }),
      Components({
        // 指定自定义组件位置(默认:src/components)
        dirs: ["src/components", "src/**/components"],
      }),
    ],
    css: {
      preprocessorOptions: {
        less: {
          javascriptEnabled: true,
          additionalData: "@root-entry-name: default;",
        },
      },
      postcss: "./postcss.config.js",
    },
    server: {
      open: false,
      host: "0.0.0.0",
    },
    resolve: {
      alias: [
        {
          find: "@",
          replacement: resolve("./src"),
        },
        {
          find: "vue-i18n",
          replacement: "vue-i18n/dist/vue-i18n.cjs.js",
        },
      ],
    },
    build: {
      cssCodeSplit: false,
      //   关闭文件计算
      reportCompressedSize: false,
      //   关闭生成map文件 可以达到缩小打包体积
      sourcemap: false, // 这个生产环境一定要关闭，不然打包的产物会很大
      minify: "esbuild", // 混淆器，terser构建后文件体积更小 esbuild
    },
    // 这么做的原因是为了支持apk的webview访问
    base: "./",
  };
});
